#include "Driver.hpp"
#include "Camera.hpp"
#include "CameraApi.h"
#include "CameraDefine.h"
#include "CameraStatus.h"
#include <format>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <vector>

MindVisionDriver::MindVisionDriver() {
  int ret = CameraSdkInit(1);
  if (ret != CAMERA_STATUS_SUCCESS)
    throw std::runtime_error(
        std::format("MindVisionDriver Can't Init Sdk ret={}", ret));
}

MindVisionDriver::~MindVisionDriver() {
  for (auto [ID, Obj] : cameraMap)
    delete Obj;
}

std::vector<std::pair<std::string, BaseCamera *>>
MindVisionDriver::GetCameraList() {
  tSdkCameraDevInfo *listptr = new tSdkCameraDevInfo[4];
  int listsize = 4;
  if (CameraEnumerateDevice(listptr, &listsize) != CAMERA_STATUS_SUCCESS)
    throw std::runtime_error("MindVisionDriver Can't scan camera");
  for (int i = 0; i < listsize; i++) {
    std::string newID = std::format("MD{}", listptr[i].acSn);
    if (cameraMap.find(newID) != cameraMap.end())
      continue;
    MindVisionCamera *newCamera = new MindVisionCamera(listptr + i);
    cameraMap.insert({newID, newCamera});
  }
  delete[] listptr;
  std::vector<std::pair<std::string, BaseCamera *>> ret;
  ret.reserve(cameraMap.size());
  for (auto [ID, Obj] : cameraMap) {
    ret.push_back({ID, dynamic_cast<BaseCamera *>(Obj)});
  }
  return ret;
}

void MindVisionDriver::CameraOffline(const std::string &uuid) {
  auto ptr = cameraMap.find(uuid);
  delete ptr->second;
  if (ptr != cameraMap.end())
    cameraMap.erase(ptr);
}
